import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

class VerifyCodeUtils {
  static String checkCode = "";

  //单位：秒
  static int randomTime = 300;

  static int minute = 0;
  static String clientSeed = "5890283734";
  static String serverSeed = "5890190293";

  ///创建时间验证码
  static String timeCode() {
    checkCode = randomCode();
    minute = (DateTime.now().millisecondsSinceEpoch ~/ 1000 ~/ 60) * 60;
    return code(clientSeed, randomTime ~/ 60);
  }

  static String code(String seed, int timeIndex) {
    String sourceStr = "000000";
    int now = minute + timeIndex * 60;
    int hash = 0;
    int i = 0;
    for (int j = 0; j < seed.length; j++) {
      int seedVal = seed.codeUnitAt(j);
      if ((i++ & 1) == 0) {
        hash ^= ((hash << 7) ^ (now % seedVal) ^ (hash >> 3));
      } else {
        hash ^= (~((hash << 11) ^ (now % seedVal) ^ (hash >> 5)));
      }
    }
    String hashStr = (hash & 0xF423F).toString();
    sourceStr =
        sourceStr.substring(0, sourceStr.length - hashStr.length) + hashStr;
    return sourceStr;
  }

  static String createCode() {
    checkCode = randomCode();
    // 获取当前时间的时间戳，单位为秒
    int timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;

    // 将时间戳转换为 32 位整型数组（大端序），用于拼接密钥
    Uint8List timestampBytes = Uint8List(4);
    ByteData.view(timestampBytes.buffer).setUint32(0, timestamp);
    return base64Url.encode(timestampBytes);
  }

  ///创建校验码
  static String randomCode() {
    String chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    Random random = Random();
    String result = '';
    for (int i = 0; i < 4; i++) {
      int index = random.nextInt(chars.length);
      result += chars[index];
    }
    return result;
  }

  ///验证码解码
  static bool decodeToken(String codeValue) {
    Uint8List byteArr = base64Url.decode(codeValue + "==");
    int intValue =
        ByteData.sublistView(Uint8List.fromList(byteArr)).getInt32(0);

    int timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    if (intValue - timestamp > 0) {
      return true;
    }
    return false;
  }

  ///验证码解码
  static bool codeState(String codeValue) {
    minute = (DateTime.now().millisecondsSinceEpoch ~/ 1000 ~/ 60) * 60;
    for (int i = 0; i < randomTime ~/ 60; i++) {
      String localCode = code(serverSeed, i);
      if (localCode == codeValue) {
        return true;
      }
    }
    return false;
  }

  ///时间转换
  static String secondsToDate(int time) {
    String minutesStr = "0";
    String secondsStr = "0";

    int minutes = time ~/ 60;
    int seconds = time % 60;

    if (minutes >= 10) {
      minutesStr = minutes.toString();
    } else {
      minutesStr = minutesStr + minutes.toString();
    }

    if (seconds >= 10) {
      secondsStr = seconds.toString();
    } else {
      secondsStr = secondsStr + seconds.toString();
    }
    return minutesStr + ":" + secondsStr;
  }
}
